// subMy/myInfo/my_info.js
import {
  sex_option
} from '../../utils/options';
import Toast from '@vant/weapp/toast/toast';
let appg = getApp().globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showpho: false,
    show_picker: false,
    show_address: false,
    value: null,
    opt_val: null, //存放操作的是电话还是学号
    option: [],
    loading: false,
    address_option: [],
    field: {
      label: "电话",
      placeholder: "请输入电话"
    },
    userInfo: {},
    // 判断是否是学生
    isStu: false,
    json: [], //存储请求回来的数据
  },
  // 年龄电话弹出层
  openShowPho(e) {
    console.log(e);
    if (e.type == "close") {
      this.setData({
        showpho: !this.data.showpho,
      })
      return;
    }
    let opt_val = e.currentTarget.dataset.opt_val
    let field = {
      label: "电话",
      placeholder: "请输入电话"
    }
    if (opt_val === "student_id") {
      field = {
        label: "学号",
        placeholder: "请输入学号"
      }
    }
    if (opt_val === "username") {
      field = {
        label: "姓名",
        placeholder: "请输入姓名"
      }
    }
    this.setData({
      showpho: !this.data.showpho,
      opt_val,
      field,
      value: this.data.userInfo[e.currentTarget.dataset.opt_val]
    })
  },
  // 号码学号确定
  confirmPho() {
    let val = 'userInfo.' + this.data.opt_val
    this.setData({
      [val]: this.data.value,
      showpho: false
    });
  },
  // 打开其他的弹出层
  async show_picker(e) {
    wx.showLoading({
      title: '数据加载中',
    })
    console.log(e);
    if (e.type == "close" || e.type == "cancel") {
      this.setData({
        show_picker: !this.data.show_picker,
      })
      wx.hideLoading()
      return;
    }
    let json_option = []
    let opt_val = e.currentTarget.dataset.opt_val
    try {
      switch (opt_val) {
        case "sex":
          wx.hideLoading()
          json_option = sex_option
          break;
        case "school_name":
          // 获取学校列表
          let json = await getApp().$axios("/getSchoolList", "GET");
          console.log(json);
          wx.hideLoading()
          if (json.status !== 200) {
            wx.showToast({
              title: json.msg,
              icon: 'error'
            });
            this.setData({
              show_picker: false,
            })
            return
          }
          this.setData({
            json: json.data
          })
          json.data.forEach(item => {
            json_option.push(item.school_name)
          });
          break;
        case "college_name":
          // 获取学院列表
          let json2 = await getApp().$axios("/getCollegeList?id=" + this.data.userInfo.school_ID, "GET");
          console.log(json2);
          wx.hideLoading()
          if (json2.status !== 200) {
            wx.showToast({
              title: json2.msg,
              icon: 'error'
            });
            this.setData({
              show_picker: false,
            })
            return
          }
          this.setData({
            json: json2.data
          })
          json2.data.forEach(item => {
            json_option.push(item.college_name)
          });
          break;
        case "class_name":
          // 获取班级列表
          let json3 = await getApp().$axios("/getClassList?id=" + this.data.userInfo.college_ID, "GET");
          console.log(json3);
          wx.hideLoading()
          if (json3.status !== 200) {
            wx.showToast({
              title: json3.data,
              icon: 'error'
            });
            this.setData({
              show_picker: false,
            })
            return
          }
          this.setData({
            json: json3.data
          })
          json3.data.forEach(item => {
            json_option.push(item.class_name)
          });
          break;
        default:
          break;
      }
    } catch (error) {
      wx.showToast({
        title: error,
      })
    }

    this.setData({
      show_picker: !this.data.show_picker,
      opt_val,
      option: json_option
    })
  },
  onConfirm(e) {
    console.log(e.detail);
    let {
      index,
      value
    } = e.detail;
    let val = 'userInfo.' + this.data.opt_val;
    // id
    let id = (this.data.opt_val).split('_').slice(0, 1);
    id.push('ID');
    let id_val = 'userInfo.' + id.join("_");
    let res = null
    if (this.data.opt_val == "sex") {
      res = value == "男" ? 0 : 1;
    } else {
      res = value
      this.setData({
        [id_val]: this.data.json[index].id,
      })
    }
    this.setData({
      [val]: res,
      show_picker: false
    });
  },
  // 打开地址选择popup
  async openAddress(e) {
    this.setData({
      show_address: !this.data.show_address
    });
    if (e.type == "close") return
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    });
    try {
      let res = await getApp().$axios('/getAddress', 'GET')
      console.log(res);
      Toast.clear()
      // 获取数据出问题
      if (res.status !== 200) {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
        return;
      }
      this.setData({
        address_option: res.data
      })
    } catch (error) {
      wx.showToast({
        title: error,
      })
    }
  },
  // 地址选择完成
  onFinish_adress(e) {
    const {
      selectedOptions,
      value
    } = e.detail;
    const fieldValue = selectedOptions
      .map((option) => option.text || option.name)
      .join('/');
    this.setData({
      'userInfo.address_name': fieldValue,
      'userInfo.adress_ID': value,
      show_address: !this.data.show_address
    });
  },
  show_Toast(e) {
    console.log(e.currentTarget.dataset.toast_val);
    let content = e.currentTarget.dataset.toast_val;
    Toast(content);
  },
  // 用户选中图片
  async bindchooseavatar(e) {
    wx.showToast({
      title: '上传成功~',
    })
    console.log(e.detail.avatarUrl, e);
    // 拿到图片信息 转base64 上传os获取在线图片地址
    let imgName = e.detail.avatarUrl;
    let imgType = null;
    // 如果需要获取图片类型的话
    wx.getImageInfo({
      src: imgName,
      success(res) {
        console.log(res);
        imgType = res.type
      }
    });
    let imgBase64 = null;
    const fs = wx.getFileSystemManager()
    // 同步接口
    try {
      const res = fs.readFileSync(e.detail.avatarUrl, 'base64', 0)
      console.log("图片的base64：", res)
      imgBase64 = res
    } catch (e) {
      wx.showToast({
        title: e,
      })
    }
    // 删除 "http://"  
    imgName = imgName.replace("http://", "");
    // // 删除文件的扩展名，包括 "."  
    // imgName = imgName.replace(/\.[^.]+$/, "");
    let json = await getApp().$axios("/uploadImg", "POST", {
      base64: `data:image/${imgType};base64,` + imgBase64,
      imgName
    })
    console.log(json, "图片在线地址");
    // appg.userInfo.avatar_url = 'https://' + json.imgUrl
    this.setData({
      "userInfo.avatar_url": 'https://' + json.imgUrl
    })
  },
  // 用户昵称
  // 用户填好昵称
  onInputChange(e) {
    console.log(e);
    // 在真机上才能生效。开发者工具有bug
    // appg.userInfo.nickname = e.detail.value
    this.setData({
      "userInfo.nickname": e.detail.value
    });
    console.log(this.data.userInfo);
  },
  // 保存
  async savePersonData() {
    try {
      let json = await getApp().$axios("/updateUserInfo", "POST", {
        ...this.data.userInfo
      })
      console.log(json);
      // 获取数据出问题
      if (json.status !== 200) {
        wx.showToast({
          title: json.msg,
          icon: 'error'
        })
        return;
      }
      appg.userInfo=json.data;
      wx.setStorageSync('userInfo', json.data)
      wx.showModal({
        title: '提示',
        content: '个人信息修改成功',
        showCancel:false,
        complete: (res) => {
          wx.switchTab({
            url: '/pages/home/home',
          })
        }
      })
    } catch (error) {
      wx.showToast({
        title: json.msg,
        icon: 'error'
      })
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userInfo: appg.userInfo,
      isStu: appg.userInfo.identity_ID == 1 ? true : false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})